<?php

class Itc_Acl extends Zend_Acl
{
    /**
     * Constructor
     *
     * @param array|Zend_Config $config acl config object
     * @return void
     */
    public function __construct($config)
    {
        if ($config instanceof Zend_Config) {
            $config = $config->toArray();
        }

        $this->rolesAdd($config['acl']['roles']);
        $this->resourcesAdd($config['acl']['resources']);
    }

    /**
     * Adds roles list to acl object
     *
     * @param array $roles roles list from config
     * @return void
     */
    public function rolesAdd($roles)
    {
        foreach ($roles as $name => $parents) {
            if (!$this->hasRole($name)) {
                if (empty($parents)) {
                    $parents = null;
                }
                else {
                    $parents = explode(',', $parents);
                }
                $this->addRole(new Zend_Acl_Role($name), $parents);
            }
        }
    }

    /**
     * Adds resources to acl object
     *
     * @param array $resources resources list from config
     * @return void
     */
    public function resourcesAdd($resources)
    {
        foreach ($resources as $permissions => $controllers) {
            foreach ($controllers as $controller => $actions) {
                if ($controller == 'all') {
                    $controller = null;
                }
                elseif (!$this->has($controller)) {
                    $this->add(new Zend_Acl_Resource($controller));
                }
                foreach ($actions as $action => $role) {
                    $role = explode(',', $role);

                    if (in_array('admin', $role)) {
                        $this->allow('admin');
                    }
                    if ($action == 'all') {
                        $action = null;
                    }

                    if ($permissions == 'allow') {
                        $this->allow($role, $controller, $action);
                    }
                    if ($permissions == 'deny') {
                        $this->deny($role, $controller, $action);
                    }
                }
            }
        }
    }

    public function hasPrivilege($resource, $privilege)
    {

        $ar = $this->_rules['byResourceId'];

        if (!isset($ar[$resource])) {
            return false;
        }

        $ar = $ar[$resource]['byRoleId'];

        foreach ($ar as $item) {
            if (isset($item['byPrivilegeId'][$privilege])) {
                return true;
            }
        }

        return false;
    }
}